package com.qbccn.onlinetest.service.impl;

import com.qbccn.onlinetest.config.KeyConfig;
import com.qbccn.onlinetest.domain.SysStyle;
import com.qbccn.onlinetest.dto.ResponseResult;
import com.qbccn.onlinetest.mapper.SysSetMapper;
import com.qbccn.onlinetest.mapper.SysStyleMapper;
import com.qbccn.onlinetest.service.ResdisService;
import com.qbccn.onlinetest.service.SystemService;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * @author linke
 * @date 2020/7/5 17:49
 * @description
 */
@Service
public class SystemServiceImpl implements SystemService {

  @Autowired
  private SysSetMapper sysSetMapper;
  @Autowired
  private SysStyleMapper sysStyleMapper;
  @Autowired
  private HttpServletRequest request;
  @Autowired
  private ResdisService resdisService;

  @Override
  public String getStyleSet() {
    Object res = resdisService.get(KeyConfig.styleKey);
    if (StringUtils.isEmpty(res)) {
      String set = thisGetStyleSet(request);
      resdisService.set(KeyConfig.styleKey, set, 60 * 60 * 8);
      return set;
    }
    return res.toString();
  }

  /**
   * 获取样式设置处理
   */
  private String thisGetStyleSet(HttpServletRequest request) {
    List<SysStyle> sysStyles = sysStyleMapper.get();
    String container = null, active = null, hover = null, nav = null;
    for (SysStyle s : sysStyles) {
      if ("container".equals(s.getCssName())) {
        container = s.getCssValue();
      } else if ("active".equals(s.getCssName())) {
        active = s.getCssValue();
      } else if ("hover".equals(s.getCssName())) {
        hover = s.getCssValue();
      } else if ("nav".equals(s.getCssName())) {
        nav = s.getCssValue();
      }
    }
    String s = String
        .format(".left-nav a:hover{%s} .left-nav a.active{%s} .container{%s} %s",
            hover, active, container, nav);
    request.getSession().setAttribute("styleType", s);
    return s;
  }

  @Override
  public List<SysStyle> getStyles() {
    return sysStyleMapper.getStyles();
  }

  @Transactional
  @Override
  public ResponseResult updateSystemStyle(Integer id) {
    SysStyle style = sysStyleMapper.selectByPrimaryKey(id);
    if (style == null) {
      return new ResponseResult(1, "样式设置异常！");
    }
    sysSetMapper.updateSystemStyle(style.getStyleType());
    String html = thisGetStyleSet(request);
    request.getSession().setAttribute(KeyConfig.styleKey, html);
    resdisService.delete(KeyConfig.styleKey);//删除redis缓存
    return new ResponseResult(0, "设置成功！", html);
  }
}
